package cn.kgc.user.config;

import cn.kgc.user.pojo.MsgListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * Created by teacher ZHANG on 2022/12/9
 */
@Configuration
public class RedisConfig {
    //将监听器加入到监听器容器中
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {
        //新建一个监听器的容器
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //容器中添加一个监听器
        container.addMessageListener(listenerAdapter, new PatternTopic("phone_code"));

        return container;
    }

    //监听器的适配器（包装类）
    @Bean
    MessageListenerAdapter listenerAdapter(MsgListener listener) {
        //注入监听器，onMessage为有消息时调用的函数
        return new MessageListenerAdapter(listener, "onMessage");
    }

}
